<template>
  <div class="box-answer">
    <div class="f jcsb aic header">
      <el-icon class="ml30 mr25 pointer" color="#3E4850" :size="20" @click="back">
        <Back />
      </el-icon>
      <div class="f14 f1 text-center">
        {{ exameInfo.exameTitle }}
      </div>
      <div class="f aic setting f12 mr20">
        <div class="f aic mr20 pointer link">
          <img style="width: 21px;height: 22px; margin-right: 7px;" src="@/assets/images/shizhong.png" />
          <div style="margin-right: 20px;">考试剩余时间：<span style="color: #FF9607;">{{
            `${timehour}:${timeminutes}:${timesecond}` }}</span></div>
        </div>
        <div class="f aic pointer link" @click="submitAnswer">
          <el-icon class="mr5">
            <DocumentChecked />
          </el-icon>
          交卷
        </div>
      </div>
    </div>

    <div class="main">
      <div class="paper relative">
        <div class="pt30 mb10 f aic jcsb">
          <div class="f aic">
            {{ currentIndex + 1 }}.
            <span v-show="currentQuestion.type == 1">
              <el-tag type="danger" class="ml10" size="small">
                单选题
              </el-tag>
              {{ paperDetails.danXuanScore }}分/题
            </span>
            <span v-show="currentQuestion.type == 2">
              <el-tag type="danger" class="ml10" size="small">
                多选题
              </el-tag>
              {{ paperDetails.duoXuanScore }}分/题
            </span>
            <span v-show="currentQuestion.type == 3">
              <el-tag type="danger" class="ml10" size="small">
                判断题
              </el-tag>
              {{ paperDetails.panDuanScore }}分/题
            </span>
          </div>
        </div>
        <div class="line40 f18" v-html="currentQuestion.questionTitle"></div>
        <div class="mt20 f18">
          <div v-if="currentQuestion.type !== 3">
            <div class="f aic mb15 pointer" v-for="(item, index) in currentQuestion.questionAnswerList" :key="index"
              :class="currentQuestion.answer ? (currentQuestion.answer.includes(item.optionLabel) ? 'active-option' : '') : ''"
              @click="handleSelectAnswerItem(item)">
              <div class="answer-sign f jcc mr10">{{ item.optionLabel }}</div>
              {{ item.content }}
            </div>
          </div>
          <el-radio-group v-else v-model="currentQuestion.answer" text-color="#12c83a" fill="#12c83a"
            class="vertical-radio-group">
            <el-radio v-for="(question, questionIndex) in judgeQuestionAnswerList" :key="questionIndex"
              :label="question.optionLabel" size="large" class="vertical-radio">{{ question.content }}</el-radio>
          </el-radio-group>
        </div>
        <!-- 答题卡 -->
        <div class="answer-card">
          <div class="f">
            <div class="f aic card-title">
              <div class="f aie">
                <div class="bold f18">答题卡</div>
                <div class="f14 ml10 total-num">
                  <span class="bold f16 black">{{ currentIndex + 1 }}</span> /
                  {{ questions.length }}
                </div>
              </div>
              <div class="arrow f aic jcc ml30 pointer" @click="showCard = !showCard">
                <el-icon v-if="showCard" color="#fff">
                  <CaretBottom />
                </el-icon>
                <el-icon v-else color="#fff">
                  <CaretTop />
                </el-icon>
              </div>
            </div>
            <div class="bb1 f1"></div>
          </div>
          <div class="question-num-box" :class="showCard ? 'open' : ''">
            <div class="pt30 pb30 f ais fw">
              <div class="question-num" v-for="(item, index) in questions" :key="index" :class="{
                'current-question': index == currentIndex,
                'sign-question': item.answer !== null && item.answer !== undefined,
              }" @click="handleChangeNumber(index)">
                {{ index + 1 }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="mt30 text-center">
        <el-button type="danger" color="#F02323" plain @click="handleLastQuestion"
          :disabled="currentIndex == 0">上一题</el-button>
        <el-button type="danger" color="#F02323" @click="handleNextQuestion"
          :disabled="currentIndex == questions.length - 1">下一题</el-button>
      </div>
    </div>
  </div>

  <!-- 交卷确认弹窗 -->
  <el-dialog v-model="submitDialogVisible" title="提示" width="30%" :close-on-click-modal="false" :append-to-body="true"
    class="custom-message-box">
    <span>是否已检查完毕，确认交卷？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 考试时间结束弹窗 -->
  <el-dialog v-model="timeoutDialogVisible" title="提示" width="30%" :close-on-click-modal="false" :append-to-body="true"
    class="custom-message-box">
    <span>答题时间已到，请交卷</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleTimeoutConfirm">交卷</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Back,
  Setting,
  DocumentChecked,
  CaretTop,
  CaretBottom,
} from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { ref, onMounted, onUnmounted } from "vue";
import { goExameInfo, getPaper, exameAnswer } from "@/api/previousExam";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
// 考试相关信息
const exameInfo = ref({});
// 答题卡
const showCard = ref(false);
// 当前题目
const questions = ref([]);
const paperDetails = ref({});
const currentIndex = ref(0);
const currentQuestion = ref({});

// 弹窗控制
const submitDialogVisible = ref(false);
const timeoutDialogVisible = ref(false);

// 答题倒计时
let timerId = null
let jiaojuanTime = 0
onMounted(() => {
  exameInfo.value = {
    exameId: route.query.exameId
  }
  console.log("🚀 ~ onMounted ~ exameInfo.value:", exameInfo.value, route)
  if (route.query.exameId && route.query.exameId.length > 0) {
    getExameInfo(exameInfo.value);
  } else {
    ElMessage.warning('试卷id为空，请返回列表重新选择！')
  }
});
onUnmounted(() => {
  // 清除定时器
  if (timerId) {
    clearInterval(timerId)
    timerId = null
  }
});
const getExameInfo = async (item) => {
  const res = await goExameInfo(item.exameId)
  console.log("🚀 ~ goExameInfo ~ response:", res)
  if (res.code === 200) {
    Object.assign(exameInfo.value, res.data)
    // 剩余时间
    jiaojuanTime = res.data.paperTime * 60
    const paperRes = await getPaper(res.data.paperId)
    if (paperRes.code === 200) {
      console.log("🚀 ~ getExameInfo ~ paperRes:", paperRes)
      paperDetails.value = paperRes.data
      // 设置题目
      const danxuanList = paperRes.data.danxuanList
      danxuanList.forEach(i => { i.type = 1 })

      const duoxuanList = paperRes.data.duoxuanList
      duoxuanList.forEach(i => { i.type = 2 })

      const panduanList = paperRes.data.panduanList
      panduanList.forEach(i => { i.type = 3 })

      questions.value = [...danxuanList, ...duoxuanList, ...panduanList];
      currentQuestion.value = questions.value[0]
      currentIndex.value = 0
      // jiaojuanTime = parseInt(props.userInfo.paperTime) * 60
    }
    // 考试时间
    timerId = setInterval(getTime, 1000)
  }
}
// 根据type 1 单选 type 2 多选 
const handleSelectAnswerItem = (item) => {

  console.log("🚀 ~ handleSelectAnswerItem ~ item:", item, questions)
  if (currentQuestion.value.type === 1) {
    currentQuestion.value.answer = [item.optionLabel]
  } else if (currentQuestion.value.type === 2) {
    if (currentQuestion.value.answer && currentQuestion.value.answer.length > 0) {
      if (currentQuestion.value.answer.includes(item.optionLabel)) {
        currentQuestion.value.answer = currentQuestion.value.answer.filter(i => i !== item.optionLabel)
      } else {
        currentQuestion.value.answer = [...currentQuestion.value.answer, item.optionLabel]
      }
    } else {
      currentQuestion.value.answer = [item.optionLabel]
    }
  }
}
// 切换题目
const handleLastQuestion = () => {
  currentIndex.value -= 1
  currentQuestion.value = questions.value[currentIndex.value]
}
const handleNextQuestion = () => {
  currentIndex.value += 1
  currentQuestion.value = questions.value[currentIndex.value]
}
// 点击切换
const handleChangeNumber = (index) => {
  currentIndex.value = index;
  currentQuestion.value = questions.value[index];
};

const submitAnswer = () => {
  submitDialogVisible.value = true;
};

const handleSubmitConfirm = () => {
  submitDialogVisible.value = false;
  submitForm();
};
function submitForm() {
  const answers = questions.value.map((item) => {
    if (item.type !== 3) {
      return {
        questionId: item.questionId,
        answer: item.answer || []
      }
    } else {
      return {
        questionId: item.questionId,
        answer: item.answer ? [item.answer] : []
      }
    }
  });
  console.log("🚀 ~ answers ~ answers:", answers)
  exameAnswer({
    stuAnswersList: answers,
    exameId: exameInfo.value.exameId,
  })
    .then((res) => {
      if (res.code === 200) {
        console.log("🚀 ~ .then ~ res:", res)
        ElMessage.success('交卷成功');
        router.replace({
          path: '/report',
          query: {
            id: exameInfo.value.exameId
          }
        })
      } else {
        ElMessage({
          message: res.msg,
          type: 'error',
        })
      }
    })
    .catch((error) => {
      console.log(error)
      ElMessage.error('交卷失败');
    });
}

const back = () => {
  history.back();
};

// 时间
const timehour = ref('00')
const timeminutes = ref('00')
const timesecond = ref('00')
// 封装时间
function getTime() {
  if (jiaojuanTime === 0) {
    timeoutDialogVisible.value = true;
    return
  }
  // 获取剩余的时间戳 记得转换为秒数
  let count = jiaojuanTime
  // 转换为时分秒
  let h = parseInt(count / 60 / 60 % 24)
  h = h < 10 ? "0" + h : h
  let m = parseInt(count / 60 % 60)
  m = m < 10 ? "0" + m : m
  let s = parseInt(count % 60)
  s = s < 10 ? "0" + s : s
  // 把时分秒写到对应的盒子里面
  timehour.value = h
  timeminutes.value = m
  timesecond.value = s
  jiaojuanTime -= 1
}
const judgeQuestionAnswerList = [
  {
    optionLabel: "正确",
    content: "正确",
  },
  {
    optionLabel: "错误",
    content: "错误",
  },
];

// 处理考试时间结束确认
const handleTimeoutConfirm = () => {
  timeoutDialogVisible.value = false;
  submitForm();
};
</script>
<style lang="scss" scoped>
@import "./index.scss";

:deep(.vertical-radio-group) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .vertical-radio {
    margin-bottom: 15px;
    /* 单选按钮文字样式 */
    .el-radio__label {
      font-size: 18px;
    }
    
    .el-radio__input.is-checked + .el-radio__label {
      color: #12c83a;
    }
    .el-radio__input {
      .el-radio__inner {
        width: 32px;
        height: 32px;
        border-color: #d6d6d6;

        &::after {
          width: 16px;
          height: 16px;
          background-color: #12c83a;
        }
      }

      &.is-checked {
        .el-radio__inner {
          border-color: #12c83a;
          background: #fff;
        }

        .el-radio__label {
          border-color: #12c83a;
          background: #fff;
        }
      }
    }
  }
}

:deep(.custom-message-box) {
  .el-dialog__header {
    padding: 15px 20px;
    margin-right: 0;
    border-bottom: 1px solid #eee;
  }

  .el-dialog__body {
    padding: 20px;
    font-size: 16px;
    color: #606266;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    text-align: right;
  }

  .dialog-footer {
    .el-button {
      padding: 8px 20px;
      font-size: 14px;

      &.el-button--primary {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }
}
</style>
